package com.zx.idc.backend.gui.api.ws.services.handler.strategy.command.base;

import com.zx.idc.backend.gui.api.commom.base.BaseIDCCommand;
import com.zx.idc.backend.gui.api.commom.entity.CommandModel;
import com.zx.idc.backend.gui.api.commom.factory.ReturnFactory;
import org.springframework.util.ObjectUtils;
import java.lang.reflect.ParameterizedType;
import java.util.concurrent.CompletableFuture;

/**
 * Created by hasee on 2019/2/22.
 */
public abstract class CommandOperating<T> extends BaseIDCCommand {


    /**
     * @param xmlData
     * @param commandModel
     * @param schemaPath
     * @return
     */
    public String receiveCommand(String xmlData, CommandModel commandModel, String schemaPath) {
        Class<T> genericClass = getFirstGenericClass();
        T xmlBean = xml2Bean(xmlData, genericClass, schemaPath);
        LOG.debug("xml字符串转换bean:{}", xmlBean);
        if (!ObjectUtils.isEmpty(xmlBean)) {
            //扔进异步任务里面执行相应的指令
            LOG.debug("扔进异步任务里面执行相应的指令");
            CompletableFuture.runAsync(() -> task(xmlBean, commandModel));
            LOG.debug("指令调用成功");
            return ReturnFactory.getOKReturn("成功");
        }
        LOG.debug("xml字符串转换bean失败,文件格式验证异常");
        return ReturnFactory.getFormatExceptionReturn("文件格式验证异常");
    }

    /**
     * 覆盖该方法执行指令
     *
     * @param t            实体bean
     * @param commandModel 指令mode
     */
    public abstract void task(T t, CommandModel commandModel);


    /**
     * 获取类的第一个泛型Class
     *
     * @return 泛型Class
     */
    protected Class<T> getFirstGenericClass() {
        ParameterizedType ptype = (ParameterizedType) this.getClass().getGenericSuperclass();
        return (Class<T>) ptype.getActualTypeArguments()[0];
    }
}
